//
//  JCLToolbar.swift
//  表情键盘
//
//  Created by DDC on 2017/9/27.
//  Copyright © 2017年 DDC. All rights reserved.
//

import UIKit

// 添加代理协议
@objc protocol JCLToolbarDelegate: NSObjectProtocol {
    
    func jcl_toolbarDelegateSelectedIndex(toolbar:JCLToolbar,index:Int)
}

class JCLToolbar: UIView {
    
    // 设置代理属性
    weak var delegate:JCLToolbarDelegate?
    
    // 设置选中toolbar按钮的index
    var selectedIndex:Int = 0 {
        didSet {
            
            // 遍历所有按钮,取消选中状态
            for btn in subviews as! [UIButton] {
                
                btn.isSelected = false
            }
            // 将所选按钮的选中状态打开
            (subviews[selectedIndex] as! UIButton).isSelected = true
        }
    }

    override func awakeFromNib() {
        
        setupUi()
    }
    
    /// 设置布局
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let count = subviews.count
        let width = bounds.width / CGFloat(count)
        let rect = CGRect(x: 0, y: 0, width: width, height: bounds.height)
        
        for (i,btn) in subviews.enumerated() {
            
            btn.frame = rect.offsetBy(dx:CGFloat(i) * width, dy: 0)
        }
    }
    // MARK:  - toolbar按钮点击事件
    @objc func clickToolBarButton(button:UIButton) {
        
        delegate?.jcl_toolbarDelegateSelectedIndex(toolbar: self, index: button.tag)
    }

}
extension JCLToolbar {
    func setupUi() {
        
        let manager = JCLEmoticonsManager.shared
        
        for (i,p) in manager.packages.enumerated() {
            
            let btn = UIButton()
            btn.setTitle(p.groupName, for: [])
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
            btn.setTitleColor(UIColor.white, for: [])
            btn.setTitleColor(UIColor.red, for: .selected)
            btn.setTitleColor(UIColor.red, for: .highlighted)
            
            btn.sizeToFit()
            addSubview(btn)
            
            // 按钮点击事件
            btn.addTarget(self, action: #selector(clickToolBarButton), for: .touchUpInside)
            // 设置按钮的tag值
            btn.tag = i
        }
        // 默认选中第一个按钮
        (subviews[0] as! UIButton).isSelected = true
    }
}


